General rule

Please show your work and submit your computer codes in order to get points. Providing correct answers without supporting details does not receive full credits. This HW covers:

For an assignment or project, you DO NOT have to submit your answers or reports using typesetting software. However, your answers must be well organized and well legible for grading. Please upload your answers in a document to the course space. Specifically, if you are not able to knit a .Rmd/.rmd file into an output file such as a .pdf, .doc, .docx or .html file that contains your codes, outputs from your codes, your interpretations on the outputs, and your answers in text (possibly with math expressions), please organize your codes, their outputs and your answers in a document in the format given below:

Problem or task or question ... 
Codes ...
Outputs ...
Your interpretations ...

It is absolutely not OK to just submit your codes only. This will result in a considerable loss of points on your assignments or projects.

Problem 1

Please refer to the NYC flight data nycflights13 that has been discussed in the lecture notes and whose manual can be found at https://cran.r-project.org/web/packages/nycflights13/index.html. We will use flights, a tibble from nycflights13.

You are interested in looking into the average arr_delay for 4 different month 12, 1, 7 and 8, for 3 different carrier “UA”, “AA” and “DL”, and for distance that are greater than 700 miles, since you suspect that colder months and longer distances may result in longer average arrival delays. Note that you need to extract observations from flights, and that you are required to use dplyr for this purpose.

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(nycflights13)
flights1 = flights %>% filter(month %in% c(12, 1, 7, 8), carrier %in% c("UA", "AA", "DL"), distance > 700) #extract observations
flights1 = na.omit(flights1)
flights1 = flights1 %>% mutate_at('month', as.factor)
head(flights1)
## # A tibble: 6 × 19
##    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time
##   <int> <fct> <int>    <int>          <int>     <dbl>    <int>          <int>
## 1  2013 1         1      517            515         2      830            819
## 2  2013 1         1      533            529         4      850            830
## 3  2013 1         1      542            540         2      923            850
## 4  2013 1         1      554            600        -6      812            837
## 5  2013 1         1      554            558        -4      740            728
## 6  2013 1         1      558            600        -2      753            745
## # ℹ 11 more variables: arr_delay <dbl>, carrier <chr>, flight <int>,
## #   tailnum <chr>, origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>,
## #   hour <dbl>, minute <dbl>, time_hour <dttm>

The following tasks and questions are based on the extracted observations.

(1.a) For each combination of the values of carrier and month, obtain the average arr_delay and obtain the average distance. Plot the average arr_delay against the average distance, use carrier as facet; add a title “Base plot” and center the title in the plot. This will be your base plot, say, as object p. Show the plot p.

library(ggplot2)
summary_stats = flights1 %>% group_by(month, carrier) %>% summarise(mean_arr_delay = mean(arr_delay), mean_distance = mean(distance))
## `summarise()` has grouped output by 'month'. You can override using the
## `.groups` argument.
p = ggplot(summary_stats, aes(x = mean_distance, y = mean_arr_delay)) + geom_point() + ggtitle("Base Plot") + theme(plot.title = element_text(hjust = 0.5)) + facet_wrap(~carrier)
p

(1.b) Modify p as follows to get a plot p1: connect the points for each carrier via one type of dashed line; code the 3 levels of carrier as \(\alpha_1\), \(\beta_{1,2}\) and \(\gamma^{[0]}\), and display them in the strip texts; change the legend title into “My \(\zeta\)” (this legend is induced when you connect points for each carrier by a type of line), and put the legend in horizontal direction at the bottom of the plot; add a title “With math expressions” and center the title in the plot. Show the plot p1.

carrier_map = c(expression(alpha[1]),  expression(beta[1*","*2]), expression(gamma^'[0]'))
p1 = p + geom_line(aes(group = carrier, linetype = carrier)) + labs(linetype = expression(paste("My ", zeta, sep = ""))) + scale_linetype_discrete(labels = carrier_map)
p1

(1.c) Modify p1 as follows to get a plot p2: set the font size of strip text to be 12 and rotate the strip texts counterclockwise by 15 degrees; set the font size of the x-axis text to be 10 and rotate the x-axis text clockwise by 30 degrees; set the x-axis label as “\(\hat{\mu}\) for mean arrival delay”; add a title “With front and text adjustments” and center the title in the plot. Show the plot p2

p2 = p1 + theme(
    strip.text = element_text(size = 12, angle = -15),
    axis.text.x = element_text(size = 10, angle = 30, hjust = 1),
    plot.title = element_text(hjust = 0.5),
    axis.title.x = element_text(size = 12)
  ) +
  labs(
    x = expression(paste(hat(mu), " for mean arrival delay", sep = ""))
  ) +
  ggtitle("With font and text adjustments")

print(p2)

Problem 2

This problem requires you to visualize the binary relationship between members of a karate club as an undirected graph. Please install the R library igraphdata, from which you can obtain the data set karate and work on it. Create a graph for karate. Once you obtain the graph, you will see that each vertex is annotated by a number or letter. What do the numbers or letters refer to? Do you see subgraphs of the graph? If so, what do these subgraphs mean?

library(igraph)
## 
## Attaching package: 'igraph'
## The following objects are masked from 'package:dplyr':
## 
##     as_data_frame, groups, union
## The following objects are masked from 'package:stats':
## 
##     decompose, spectrum
## The following object is masked from 'package:base':
## 
##     union
library(igraphdata)
data(karate)
?karate
plot(karate)
## This graph was created by an old(er) igraph version.
##   Call upgrade_graph() on it to use with the current igraph version
##   For now we convert it on the fly...

Each node, represented by a number or letter refers to one of the 34 different members of a karate club. Additionally the letters separate the leaders from the members of the club(s?), A is John A the president, and H is Mr. Hi the instructor. There are two sub-graphs present marked by a change in color, orange or blue. This refers to the two different factions of the karate club after it was split into two separate clubs due to the dispute between the president and the instructor.

Problem 3

This problem requires to to create an interactive plot using plotly. If you want to display properly the plot in your HW answers, you may well need to set your HW document as an html file (instead of doc, docx or pdf file) when you compile your R codes.

Please use the mpg data set we have discussed in the lectures. Create an interactive, scatter plot between “highway miles per gallon” hwy (on the y-axis) and “engine displacement in litres” displ (on the x-axis) with the color aesthetic designated by “number of cylinders” cyl, and set the x-axis label as “engine displacement in litres” and y-axis label as “highway miles per gallon”. You need to check the object type for cyl and set it correctly when creating the plot. Add the title “# of cylinders” to the legend and adjust the vertical position of the legend, if you can. For the last, you may look through https://plotly.com/r/legend/ for help.

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:igraph':
## 
##     groups
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
head(mpg)
## # A tibble: 6 × 11
##   manufacturer model displ  year   cyl trans      drv     cty   hwy fl    class 
##   <chr>        <chr> <dbl> <int> <int> <chr>      <chr> <int> <int> <chr> <chr> 
## 1 audi         a4      1.8  1999     4 auto(l5)   f        18    29 p     compa…
## 2 audi         a4      1.8  1999     4 manual(m5) f        21    29 p     compa…
## 3 audi         a4      2    2008     4 manual(m6) f        20    31 p     compa…
## 4 audi         a4      2    2008     4 auto(av)   f        21    30 p     compa…
## 5 audi         a4      2.8  1999     6 auto(l5)   f        16    26 p     compa…
## 6 audi         a4      2.8  1999     6 manual(m5) f        18    26 p     compa…
mpg = mpg %>% mutate_at('cyl', as.factor)
myplotly = plot_ly(mpg, x = ~displ, y = ~hwy, color = ~cyl, type = "scatter") %>% layout(xaxis=list(title="engine displacement in litres"), yaxis=list(title="highway miles per gallon")) %>% layout(legend=list(title=list(text="# of cylinders"))) %>% layout(legend = list(x = 100, y = 0.5))
myplotly
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode